package com.colinsage.dpap.dao.plugin;

import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.mapping.MappedStatement.Builder;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import com.deppon.foss.framework.server.components.dataaccess.dialect.Dialect;
import com.deppon.foss.framework.server.components.dataaccess.ibatis.OffsetLimitInterceptor.BoundSqlSqlSource;
import com.deppon.foss.framework.shared.util.PropertiesHelper;


/*
 *2011-4-2
 *需要完善的功能
 *1、判断是否分页（参数中有RowBounds），如果分页了就不进行限制
 *2、如果方言不支持限制行数，则
 */
@Intercepts({ @Signature(type = Executor.class, method = "query", args = {
		MappedStatement.class, Object.class, RowBounds.class,
		ResultHandler.class }) })
public class PrintSqlIntercepter implements Interceptor {
	final static Log log = LogFactory.getLog(PrintSqlIntercepter.class);

	Dialect dialect;

	public Object intercept(Invocation invocation) throws Throwable {
		Object[] queryArgs = invocation.getArgs();
		MappedStatement ms = (MappedStatement) queryArgs[MyBatisInstant.MAPPED_STATEMENT_INDEX];
		Object parameter = queryArgs[MyBatisInstant.PARAMETER_INDEX];
		BoundSql bsql = ms.getBoundSql(parameter);
		String sql = bsql.getSql().trim();

		if (log.isInfoEnabled()) {
			log.info("[DAO]Before limit: " + sql);
		}

		if (dialect.supportsLimit()) {
			sql = dialect.getLimitString(sql, 0, MyBatisInstant.ROW_LIMIT);
		} else {
			if (log.isInfoEnabled()) {
				log.info("dialect not support limit");
			}
			return invocation.proceed();
		}
		if (log.isInfoEnabled()) {
			log.info("[DAO]After limit: " + sql);
		}
		BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), sql,
				bsql.getParameterMappings(), bsql.getParameterObject());
		MappedStatement newMs = copyFromMappedStatement(ms,
				new BoundSqlSqlSource(newBoundSql));
		queryArgs[MyBatisInstant.MAPPED_STATEMENT_INDEX] = newMs;

		return invocation.proceed();
	}

	private MappedStatement copyFromMappedStatement(MappedStatement ms,
			SqlSource newSqlSource) {
		Builder builder = new MappedStatement.Builder(ms.getConfiguration(),
				ms.getId(), newSqlSource, ms.getSqlCommandType());

		builder.resource(ms.getResource());
		builder.fetchSize(ms.getFetchSize());
		builder.statementType(ms.getStatementType());
		builder.keyGenerator(ms.getKeyGenerator());
		builder.keyProperty(ms.getKeyProperty());

		// setStatementTimeout()
		builder.timeout(ms.getTimeout());

		// setStatementResultMap()
		builder.parameterMap(ms.getParameterMap());

		// setStatementResultMap()
		builder.resultMaps(ms.getResultMaps());
		builder.resultSetType(ms.getResultSetType());

		// setStatementCache()
		builder.cache(ms.getCache());
		builder.flushCacheRequired(ms.isFlushCacheRequired());
		builder.useCache(ms.isUseCache());

		return builder.build();
	}

	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	public void setProperties(Properties properties) {
		String dialectClass = new PropertiesHelper(properties)
				.getRequiredString("dialectClass");
		try {
			dialect = (Dialect) Class.forName(dialectClass).newInstance();
		} catch (Exception e) {
			throw new RuntimeException(
					"cannot create dialect instance by dialectClass:"
							+ dialectClass, e);
		}
	}
}
